package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.BranchNo;
import com.jh.paymentchannel.pojo.JFRegister;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;

import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class JFpageRequest {

	private static final Logger log = LoggerFactory.getLogger(JFpageRequest.class);


	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jf.partnerNo}")
	private String partnerNo;
	
	@Value("${jf.key}")
	private String Key;
	
	@Value("${jf.url}")
	private String JFurl;
	
/*	private static String partnerNo = "UDp0WZ64";

	private static String Key = "UD1RDD194BDVDPCCUB56434C39EWZE98";

	private String JFurl = "http://fast.jfpays.com:19083";*/
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	/**
	 * 进件接口
	 *
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jf/register")
	public @ResponseBody Object jfRegister(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName
		)
			  throws Exception {
		log.info("开始进入进件接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		/** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 通道id
		String channelid = resultObj.getString("channelid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		// 根据银行名称查询得到银行信息
		BranchNo findByBankName;
		try {
			findByBankName = branchbankBussiness.findByBankName(bankName);
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行信息有误");
			return map;
		}
		// 银行总行联行号
		String inBankUnitNo = findByBankName.getBankNo();

		//随机获取商铺信息表中的商户数据
		//String shopUserId = Util.shops();
		
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		
		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject =  JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			log.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "sdj");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}
		
		log.info("随机获取的userId"+shopUserId);
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		String shopName = resultObj.getString("name");// 商户全称
		String address = resultObj.getString("address");// 注册地址
		String shopsAddress = resultObj.getString("shopsaddress");

		String Address = address + shopsAddress;


		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/find/province";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
		} catch (Exception e) {
			log.error("查询商铺省市出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "该商铺省市信息有误");
			return map;
		}
		String province = jsonObject.getString("province");
		String city = jsonObject.getString("city");
		
		
		String orderNo = getNumberOrderCode();
		// 进件接口的交易代码
		String txnCode = "101001";
		String api = "/rest/api/"+txnCode;
		
		//生成一个8位随机数
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String merchantCode = uuid.substring(0, 8);
		
		String substring = uuid.substring(8, 11);
		
		String t0TxnFee = "";
		Double valueOf = Double.valueOf(extraFee);
		if(valueOf!=0&&valueOf>2){
			String extrafee = new BigDecimal(valueOf.toString()).multiply(new BigDecimal("100")).setScale(0).toString();
			t0TxnFee = extrafee;
		}else{
			t0TxnFee = "200";
		}
		
		JSONObject dto = new JSONObject();
		dto.put("merchantCode", merchantCode);// 商户号
		dto.put("merchantName", shopName+substring);// 商户名称
		dto.put("province", province);// 商户所在省份
		dto.put("city", city);// 商户所在城市
		dto.put("address", Address);// 商户所在详细地址
		dto.put("cardHolderName", userName);// 持卡人姓名
		dto.put("mobile", phone);// 手机号
		dto.put("idCard", idcard);// 身份证
		dto.put("inBankCardNo", cardNo);// 入账银行卡号
		dto.put("inBankName", bankName);// 银行名称
		dto.put("inBankUnitNo", inBankUnitNo);// 银行总行联行号
		dto.put("t0TxnRate", rate);// 消费交易手续费扣率
		// Strings.isNullOrEmpty(t0TxnFee) ? "0" : t0TxnFee
		dto.put("t0TxnFee", t0TxnFee);// 单笔消费交易手续费
		dto.put("operateType", "A");// 操作类型(A:新增 M:修改)
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));
		
		//ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);
				
		String res;
		//返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
			
			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject======="+jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			log.info("head======="+head);
			respCode = head.getString("respCode");
			log.info("respCode====="+respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======"+respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，进件失败啦！");
			return map;
		}
        
        //进件成功
        if("000000".equals(respCode)&&"success".equals(respMsg)){
        	//进件成功返回的商户号
            String platMerchantCode = jsonObject.getString("platMerchantCode");
        	JFRegister jfRegister = topupPayChannelBusiness.getJFRegister(Long.parseLong(userid));
        	
        	String fee = Double.valueOf(t0TxnFee)/100+"";
        	if(jfRegister == null){
        		log.info("用户第一次进件======");
        		JFRegister jfR = new JFRegister();
        		jfR.setBankCard(cardNo);
        		jfR.setFee(fee);
        		jfR.setJFUserId(platMerchantCode);
        		jfR.setRate(rate);
        		jfR.setMerchantCode(merchantCode);
        		jfR.setUserId(Long.parseLong(userid));
        		
        		try {
					topupPayChannelBusiness.createJFRegister(jfR);
				} catch (Exception e) {
					map.put("resp_code", "failed");	
			        map.put("channel_type", "jfcoin");
					map.put("resp_message", "保存首次进件信息失败");
					return map;
				}
        	}else {
        		log.info("用户信息修改后重新进件======");
        		jfRegister.setBankCard(cardNo!=null&&!cardNo.equals("")?cardNo:jfRegister.getBankCard());
        		jfRegister.setFee(fee);
        		jfRegister.setJFUserId(platMerchantCode!=null&&!platMerchantCode.equals("")?platMerchantCode:jfRegister.getJFUserId());
        		jfRegister.setRate(rate!=null&&!rate.equals("")?rate:jfRegister.getRate());
        		jfRegister.setMerchantCode(merchantCode!=null&&!merchantCode.equals("")?merchantCode:jfRegister.getMerchantCode());
                
                try {
					topupPayChannelBusiness.createJFRegister(jfRegister);
				} catch (Exception e) {
					log.error("保存重新进件信息失败");
					map.put("resp_code", "failed");	
			        map.put("channel_type", "jfcoin");
					map.put("resp_message", "保存重新进件信息失败");
					return map;
				}
        	}
        
            
			log.info("进件成功================"+res);
	        log.info("开始交易==============");
				
	       map = (Map) this.jfPay(request,ordercode,provinceOfBank,cityOfBank,bankBranchName);
	       return map;
	       
			
        }else{
        	log.info("进件失败=====");
            map.put("resp_code", "failed");	
    		map.put("channel_type", "jf");
    		map.put("resp_message", respMsg);
    		return map;
        }
        
        
	}

	 
	 
	/*
	 * 支付接口
	 * 
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jf/pay")
	public @ResponseBody Object jfPay(HttpServletRequest request,
	 		@RequestParam(value = "ordercode") String ordercode,
	 		@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName
		)
			throws Exception {
		
		log.info("开始进入支付接口========================");
		Map<String, String> maps = new HashMap<String, String>();
		//** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **//*
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 通道id
		String channelid = resultObj.getString("channelid");
		// 费率
		String rate = resultObj.getString("rate");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		String amount = resultObj.getString("amount");
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询默认结算卡有误");
			return maps;
		}

		if (resultObj.isNullObject()) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		
		
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询银行卡信息有误");
			return maps;
		}
		String mobile = resultObj.getString("phone"); //预留信用卡手机号码
		String idcard = resultObj.getString("idcard");//身份证号
		String userName = resultObj.getString("userName");//用户姓名
		String bankName = resultObj.getString("bankName");
		
/*		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询商铺信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询商铺信息有误");
			return maps;
		}

		String shopName = resultObj.getString("name");// 商户全称
		String address = resultObj.getString("address");// 注册地址
		String shopsAddress = resultObj.getString("shopsaddress");

		String Address = address + shopsAddress;*/

		// 根据银行名称查询得到银行信息
		BranchNo findByBankName = branchbankBussiness.findByBankName(bankName);
		// 银行总行联行号
		String inBankUnitNo = findByBankName.getBankNo();

		// 支付接口的交易代码
		String paytxnCode = "102001";
		String payapi = "/rest/api/"+paytxnCode;
		
		
		//根据userid去查询用户进件表
		JFRegister jfRegister = topupPayChannelBusiness.getJFRegister(Long.parseLong(userid));
		//获得用户进件成功返回的商户号
		String jfUserId = jfRegister.getJFUserId();
		String fees = jfRegister.getFee();
		
		JSONObject dto = new JSONObject();
		dto.put("frontNotifyUrl", ipAddress+"/v1.0/paymentchannel/topup/jf/return_call");// 前台通知地址URL
		dto.put("backNotifyUrl", ipAddress+"/v1.0/paymentchannel/topup/jf/notify_call");// 后台通知地址URL
		dto.put("platMerchantCode", jfUserId);// 入网成功返回的商户号
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time = format.format(date);
		
		dto.put("cutDate", time);// 当前日期

		// 将订单总金额转换为以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();

		dto.put("txnAmt", Amount);// 订单总金额(以分为单位)
		dto.put("cardHolderName", userName);// 持卡人姓名
		dto.put("mobile2", mobile);// 充值卡手机号码(非必填)
		dto.put("idCard", idcard);// 身份证
		dto.put("inBankCardNo", cardNo);// 入账银行卡号
		dto.put("payBankCardNo", bankCard);// 支付银行卡号
		dto.put("inBankName", bankName);// 银行名称
		dto.put("inBankUnitNo", inBankUnitNo);// 总行联行号
		
		Double drate = Double.valueOf(rate.trim());
		log.info("drate============="+drate);
		Double damount = Double.valueOf(amount.trim());
		log.info("damount============="+damount);
		Double dfees = Double.valueOf(fees.trim());
		log.info("dfees============="+dfees);
		    
		
		
		//单笔固定手续费
		String t0TxnFee = new BigDecimal(fees).multiply(new BigDecimal("100")).setScale(0).toString();
		//手续费
		BigDecimal bigamount = new BigDecimal(amount);
		BigDecimal bigrate = new BigDecimal(rate);
		//Bigcecimal类型的运算
		BigDecimal multiply = bigamount.multiply(bigrate);
		
		//String d = multiply.toString();
		//String d = Double.valueOf(amount)*Double.valueOf(rate)+"";
		//BigDecimal bd = new BigDecimal(d);
		
		//小数点后2位向上进1位
		BigDecimal setScale = multiply.setScale(2, RoundingMode.CEILING);
		//String string = String.format("%.2f", d).toString();
		String fee = new BigDecimal(setScale+"").multiply(new BigDecimal("100")).setScale(0).toString();
		
		//到账金额
		String inTxnAmt = Long.valueOf(Amount)-Long.valueOf(t0TxnFee)-Long.valueOf(fee)+"";
		
		
		log.info("t0TxnFee=========="+t0TxnFee);
		log.info("fee=========="+fee);
		log.info("inTxnAmt=========="+inTxnAmt);
		
		
		dto.put("inTxnAmt", inTxnAmt);// 到账金额
		dto.put("t0TxnRate", rate);// 消费交易手续费扣率
		dto.put("t0TxnFee", t0TxnFee);// 单笔消费交易手续费
		dto.put("fee", fee);// 手续费(手续费=费率*交易金额)
		

		dto.put("head", this.getHead(ordercode, partnerNo, paytxnCode));
		log.info("dto======"+dto);
		String execute = this.execute(Key, JFurl, payapi, dto.toString(), partnerNo, ordercode);
		log.info(execute);
				
		String res;
		//返回状态码
		String respCode;
		String respMsg;
		String pageContent;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			log.info("hahahha========="+resJson);
			String sign = resJson.getString("signature");
			log.info("hahahha========="+sign);
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
			log.info("hahahha========="+res);

			com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res);
			
			com.alibaba.fastjson.JSONObject head = json.getJSONObject("head");
			respCode = head.getString("respCode");
			respMsg = head.getString("respMsg");
			pageContent = json.getString("pageContent");
		} catch (Exception e1) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "亲,支付失败啦");
			return maps;
		}
        
        
        log.info("pageContent====="+pageContent);
        Map mapp = new HashMap();
        //支付成功
        if("000000".equals(respCode)&&"success".equals(respMsg)){
        	
        	
        	restTemplate = new RestTemplate();
    		uri = util.getServiceUrl("user", "error url request!");
    		url = uri.toString() + "/v1.0/user/bank/update/bynewcardno";
    		requestEntity = new LinkedMultiValueMap<String, String>();
    		requestEntity.add("cardNo", cardNo);
    		requestEntity.add("province", provinceOfBank);
    		requestEntity.add("city", cityOfBank);
    		requestEntity.add("bankBranchName", bankBranchName);
    		result = restTemplate.postForObject(url, requestEntity, String.class);

    		log.info("RESULT================" + result);
    		try {
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("更新银行信息出错");
				maps.put("resp_code", "failed");
				maps.put("channel_type", "jf");
				maps.put("resp_message", "更新银行信息有误");
				return maps;
			}
        	
        	log.info("请求支付接口成功==================="+res);
			mapp.put("resp_code", "success");
			mapp.put("channel_type", "jf");
			mapp.put("pageContent", pageContent);	
			//mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpaysuccess");
			
			return mapp;
    		
        }else {
        	log.info("请求支付接口失败==================="+res);
			mapp.put("resp_code", "failed");
			mapp.put("channel_type", "jf");
			mapp.put("resp_message", respMsg);
			return mapp;
        }
        
		
	}

	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);
			
			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	 
    
	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}
	
	
	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jf/queryjfid")
	public @ResponseBody Object findJFRegisterUserId(HttpServletRequest request,
			@RequestParam(value = "user_id") long userid) {

		JFRegister jfRegister = topupPayChannelBusiness.getJFRegister(userid);
		Map map = new HashMap();

		if (jfRegister == null) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESULT, jfRegister);
			map.put(CommonConstants.RESP_MESSAGE, "失败");
			return map;

		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, jfRegister);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}

	}
	
	public String getNumberOrderCode(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date now = new Date();
		StringBuffer sb = new StringBuffer(sdf.format(now));
		Random random = new Random();
		for(int i = 0;i < 18;i++){
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}
	
}